/* eslint-disable prettier/prettier */
import * as THREE from 'three'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js'

class ThreeScene {
  constructor(mapData) {
    this.mapData = mapData
    this.width = window.innerWidth - mapData.width
    this.height = window.innerHeight - mapData.height

    // 创建场景、摄像机和渲染器
    this.scene = new THREE.Scene()
    this.camera = new THREE.PerspectiveCamera(45, this.width / this.height, 10, 5000)
    this.renderer = new THREE.WebGLRenderer({
      antialias: true,
      alpha: true
    })

    // 创建控制器
    this.controls = new OrbitControls(this.camera, this.renderer.domElement)
    this.allMeshGroup = new THREE.Group()
    this.allMeshGroup.name = '精灵模型'

    this.initLights()
    this.initControls()

    // 设置渲染器像素比和大小
    this.renderer.setPixelRatio(window.devicePixelRatio * 1.5)
    this.renderer.setSize(this.width, this.height)
    this.renderer.setClearColor(0xe5e7ed, 1)

    window.addEventListener('resize', () => this.onWindowResize())

    // 启动渲染循环
    this.render()
  }

  // 初始化灯光
  initLights() {
    // 环境光
    const ambient = new THREE.AmbientLight(0xffffff, 0.6)
    this.scene.add(ambient)

    // 平行光
    const directionalLight = new THREE.DirectionalLight(0xffffff, 0.4)
    directionalLight.position.set(0, 100, 0)
    this.scene.add(directionalLight)

    // 半球光
    const hemisphereLight = new THREE.HemisphereLight(0xffffff, 0x000000, 0.12)
    hemisphereLight.position.set(0, 1, 0)
    this.scene.add(hemisphereLight)
  }

  // 初始化控制器
  initControls() {
    this.controls.enableDamping = true // 启用阻尼
    this.controls.dampingFactor = 0.6 // 阻尼系数
    this.controls.enableRotate = true // 允许旋转
    this.controls.maxPolarAngle = Math.PI / 2.5 // 最大垂直旋转角度
    this.controls.panSpeed = 2 // 平移速度
    this.controls.minDistance = 100 // 最小距离
    this.controls.maxDistance = 2500 // 最大距离
    this.controls.enablePan = true // 启用右键拖拽
  }

  // 设置相机位置和控制器目标
  setCamera(position, lookAt) {
    this.camera.position.set(position.x, position.y, position.z)
    this.camera.lookAt(lookAt.x, lookAt.y, lookAt.z)
    this.controls.target.set(lookAt.x, lookAt.y, lookAt.z)
  }

  // 窗口大小改变时更新相机和渲染器
  onWindowResize() {
    this.width = window.innerWidth - this.mapData.width
    this.height = window.innerHeight - this.mapData.height
    this.camera.aspect = this.width / this.height
    this.camera.updateProjectionMatrix()
    this.renderer.setSize(this.width, this.height)
  }

  // 渲染场景
  render() {
    requestAnimationFrame(() => this.render())
    this.controls.update()
    this.renderer.render(this.scene, this.camera)
  }

  // 初始化场景并返回渲染器的DOM元素
  init(position, lookAt) {
    this.setCamera(position, lookAt)
    return this.renderer.domElement
  }
}

export { ThreeScene }
